package com.wowangz.cms.dailyoperation.services.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.services.pojo.Menu;
import com.wowangz.cms.dailyoperation.services.pojo.Services;
import com.wowangz.cms.dailyoperation.services.pojo.ServicesMenu;
import com.wowangz.cms.dailyoperation.services.service.MenuService;
import com.wowangz.cms.dailyoperation.services.service.ServicesMenuService;
import com.wowangz.cms.dailyoperation.services.service.ServicesService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;

@Scope("prototype")
@Controller
public class ServicesController extends BaseController{

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(ServicesController.class);
	
	/**
	 * 点击菜单"服务管理"显示“服务管理”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/services/queryServicesList.web")
	public String queryServicesList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/dailyoperation/services/servicesList";
	}
	
	/**
	 * 打开“服务管理”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/dailyoperation/services/queryServicesListInfoDataGrid.json")
	public void queryServicesListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, false);
			long resultCount = servicesService.findResultCount(map);
			List<Services> resultList = servicesService.findResultList(map);
			//判断服务能否删除
			for (Services services : resultList)
			{
				services.setCandelete(SysConstant.YesOrNo.YES);
				map.put("serviceid", services.getId());
				long count = servicesService.findMenuListByServiceID(map);
				if(count > 0)
				{
					services.setCandelete(SysConstant.YesOrNo.NO);
				}
			}
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("servicenum", DataTypeConstant.STRING);
			dataStyle.addDepict("servicename", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("checkstatus", SysConstant.CheckStatus.class, "getName", new Class[]{long.class});
			dataStyle.addDepictByFunction("businessstatus", SysConstant.CommonUsedStatus.class, "getName", new Class[]{long.class});
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转服务添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/services/toAddServices.web")
	public String toAddServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/dailyoperation/services/servicesAdd";
	}
	
	/**
	 * 获取菜单资源
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param writer
	 * @throws ControllerException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/dailyoperation/services/queryMenuDirectoryTree.json", method=RequestMethod.POST)
	public void queryMenuDirectoryTree(HttpServletRequest request, HttpServletResponse response, Model model){

		String menucode = request.getParameter("menucode");
		//String supid = "";
		String menulevel=request.getParameter("menulevel");

		List<Menu> topNodesList=null;
		if(StringUtils.isEmpty(menucode)){
			//得到顶级菜单
			MenuService menuService = (MenuService) IssTransactionContainer.getInstance(MenuService.class, false);
			Map map = new HashMap();
			map.put("statusid", SysConstant.RecordStatus.VALID);
			map.put("menutype", SysConstant.MenuType.NORNAL);
			map.put("menulevel", 1);
			topNodesList=menuService.queryMenuLevelTopList(map);
		}else{
			//初始化非顶级菜单
			HashMap map=new HashMap();
			map.put("menucode",menucode);
			map.put("menulevel",Integer.valueOf(menulevel)+1);
			map.put("statusid",SysConstant.RecordStatus.VALID);
			MenuService menuService = (MenuService) IssTransactionContainer.getInstance(MenuService.class, false);
			topNodesList=menuService.queryOtherMenuList(map);
			if(topNodesList == null || topNodesList.size() == 0){
				return;
			}
		}
		MenuService menuService = (MenuService) IssTransactionContainer.getInstance(MenuService.class, false);
		Map map = new HashMap();
		map.put("statusid", SysConstant.RecordStatus.VALID);
		final StringBuffer json = new StringBuffer("[");
		for(Object object:topNodesList){
			 final Menu menu=(Menu)object;
			 map.put("menucode", menu.getMenucode());
			 json.append("{menucode:'").append(menu.getMenucode()).append("'")
			 .append(",menuid:'").append(menu.getId()).append("'")
			 .append(",name:'").append(menu.getMenuname()).append("'")
			 .append(",menulevel:'").append(menu.getMenulevel()).append("'")
			 .append(",isParent:").append(menuService.isParent(map)==true?"true":"false")
			 .append("}").append(",");
		}
		try {
			response.getWriter().write(json.substring(0,json.length()-1)+"]");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增服务
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/services/addServices.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		String menuids = request.getParameter("menuids");
		String[] ids = menuids.split(",");
		String menuid = "";
		Services services = null;
		ServicesMenu servicesMenu = null;
		try {
			services = (Services) ServletUtils.getParametersToBaseEntity(request, Services.class);
			services.setInputtime(new Date());
			services.setInputuserid(getUserContext().getLoginUser().getId());
			services.setModifytime(new Date());
			services.setModifyuserid(getUserContext().getLoginUser().getId());
			services.setStatusid(SysConstant.RecordStatus.VALID);
			services.setCheckstatus(SysConstant.CheckStatus.SAVE);
			services.setBusinessstatus(SysConstant.CommonUsedStatus.STOP);
			ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, true);
			//讲服务编号和服务名称添加进去，返回新增时的ID
			servicesService.addServices(services);
			
			servicesMenu = (ServicesMenu) ServletUtils.getParametersToBaseEntity(request, ServicesMenu.class);
			for(int i =0;i<ids.length;i++){
				menuid = ids[i].toString();
				servicesMenu.setMenuid(Long.parseLong(menuid));
				servicesMenu.setServiceid(services.getId());
				servicesMenu.setStatus(SysConstant.ServiceMenuStatus.NEW);
				ServicesMenuService servicesMenuService = (ServicesMenuService) IssTransactionContainer.getInstance(ServicesMenuService.class, true);
				servicesMenuService.addServicesMenu(servicesMenu);
			}
			
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/services/servicesAdd";
	}
	
	/**
	 * 验证
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/services/validattionServices.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Services services = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			services = (Services) ServletUtils.getParametersToBaseEntity(request, Services.class);
			
			ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != services.getId()){
				map.put("id", services.getId());
			}
			map.put("servicenum", services.getServicenum());
			if(!servicesService.validationServices(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "dailyoperation.services.servicesAdd.alert1")+"!\n");
			}
			map.remove("servicenum");
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转修改服务页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/services/toUpdateServices")
	public String toUpdateServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		ServicesMenuService servicesMenuService = (ServicesMenuService) IssTransactionContainer.getInstance(ServicesMenuService.class, true);
		ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, true);
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		List<ServicesMenu> list = null;
		String id = getRequest().getParameter("id");
		hashMap.put("serviceid", id);
		try {
			Services services = servicesService.findservicesById(id);
			if(services.getCheckstatus() == SysConstant.CheckStatus.SAVE){
				//如果用户要修改的服务是保存状态，则给他修改的数据 读取dy_service_menu表中status=0的数据
				hashMap.put("status", SysConstant.ServiceMenuStatus.NEW);
				list = servicesMenuService.findservicesMenuByMap(hashMap);
			}else{
				//则读取status=1的数据
				hashMap.put("status", SysConstant.ServiceMenuStatus.OLD);
				list = servicesMenuService.findservicesMenuByMap(hashMap);
			}
			
			String str_ids = "";
			for(int i =0;i<list.size();i++){
				if("".equals(str_ids)){
					str_ids = String.valueOf(list.get(i).getMenuid());
				}else{
					str_ids = str_ids +","+String.valueOf(list.get(i).getMenuid());
				}
			}
			
			model.addAttribute("services", services);
			model.addAttribute("str_ids", str_ids);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/services/servicesUpdate";
	}
	
	/**
	 * 跳转修明细页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/services/toViewServices")
	public String toViewServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		ServicesMenuService servicesMenuService = (ServicesMenuService) IssTransactionContainer.getInstance(ServicesMenuService.class, true);
		ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, true);
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		List<ServicesMenu> list = null;
		String id = getRequest().getParameter("id");
		hashMap.put("serviceid", id);
		try {
			Services services = servicesService.findservicesById(id);
			if(services.getCheckstatus() == SysConstant.CheckStatus.SAVE){
				//如果用户要修改的服务是保存状态，则给他修改的数据 读取dy_service_menu表中status=0的数据
				hashMap.put("status", SysConstant.ServiceMenuStatus.NEW);
				list = servicesMenuService.findservicesMenuByMap(hashMap);
			}else{
				//则读取status=1的数据
				hashMap.put("status", SysConstant.ServiceMenuStatus.OLD);
				list = servicesMenuService.findservicesMenuByMap(hashMap);
			}
			
			String str_ids = "";
			for(int i =0;i<list.size();i++){
				if("".equals(str_ids)){
					str_ids = String.valueOf(list.get(i).getMenuid());
				}else{
					str_ids = str_ids +","+String.valueOf(list.get(i).getMenuid());
				}
			}
			
			HashMap<String,Object> map=new HashMap<String,Object>();
			map.put("statusid",SysConstant.RecordStatus.VALID);
			map.put("menutype",SysConstant.MenuType.NORNAL);
			MenuService menuService = (MenuService) IssTransactionContainer.getInstance(MenuService.class, false);
			List<Menu> topNodesList = menuService.queryOtherMenuList(map);
			String menu_all = "";
			for(Menu menu:topNodesList){
				if("".equals(menu_all)){
					menu_all = ""+menu.getId();
				}else{
					menu_all = menu_all+","+menu.getId();
				}
			}
			
			model.addAttribute("menu_all", menu_all);
			model.addAttribute("services", services);
			model.addAttribute("str_ids", str_ids);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/services/servicesView";
	}
	
	/**
	 * 修改服务
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/services/updateServices.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		ServicesMenuService servicesMenuService = (ServicesMenuService) IssTransactionContainer.getInstance(ServicesMenuService.class, true);
		String menuids = request.getParameter("menuids");
		String[] ids = menuids.split(",");
		String menuid = "";
		ServicesMenu servicesMenu = null;
		Services services = null;
		try {
			services = (Services) ServletUtils.getParametersToBaseEntity(request, Services.class);
			services.setModifytime(new Date());
			services.setCheckstatus(SysConstant.CheckStatus.SAVE);
			services.setBusinessstatus(SysConstant.CommonUsedStatus.STOP);
			ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, true);
			servicesService.update(services);
			
			//删除上次一保存的数据
			servicesMenu = new ServicesMenu();
			servicesMenu.setServiceid(services.getId());
			//先删上一次修改的数据
			servicesMenu.setStatus(SysConstant.ServiceMenuStatus.NEW);
			servicesMenuService.deleteServicesMenu(servicesMenu);
			
			//如果菜单ID获得的值为空，则用户未有修改菜单
			if(!"".equals(menuids)){
				//再重新添加指定服务的服务菜单关系并且状态为0 表示新数据
				servicesMenu = (ServicesMenu) ServletUtils.getParametersToBaseEntity(request, ServicesMenu.class);
				for(int i =0;i<ids.length;i++){
					menuid = ids[i].toString();
					servicesMenu.setMenuid(Long.parseLong(menuid));
					servicesMenu.setServiceid(services.getId());
					servicesMenu.setStatus(SysConstant.ServiceMenuStatus.NEW);
					servicesMenuService.addServicesMenu(servicesMenu);
				}
			}
			
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/services/servicesUpdate";
	}
	
	/**
	 * 删除服务
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/services/deleteServices.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long id = Long.valueOf(getRequest().getParameter("id"));
			
			Services services = new Services();
			services.setId(id);
			services.setStatusid(SysConstant.RecordStatus.INVALID);
			servicesService.update(services);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 启用停用服务
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/services/startOrStopServices.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void startOrStopServices(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		String flag = request.getParameter("flag");
		String returnMessage = "";
		long businessstatus = 0l;
		try {
			String ids = request.getParameter("ids");
			if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonUsedStatus.STOP))) {
				businessstatus = SysConstant.CommonUsedStatus.STOP;
				returnMessage = MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.success");
			} else {
				businessstatus = SysConstant.CommonUsedStatus.START;
				returnMessage = MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.success");
			}
			ServicesService servicesService = (ServicesService) IssTransactionContainer.getInstance(ServicesService.class, false);
			if (StringUtils.isNotEmpty(ids)) {
				String[] idsStrings = ids.split(";");
				Services services = null;
				for (String string : idsStrings) {
					services = new Services();
					services.setId(Long.valueOf(string));
					services.setBusinessstatus(businessstatus);
					servicesService.update(services);
				}
				userContext.setInfoMessage(returnMessage);
			}
		} catch (Exception e) {
			if(businessstatus == SysConstant.CommonUsedStatus.START)
			{
				userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.failure")+e.getMessage());
			}else
			{
				userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.failure")+e.getMessage());
			}
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity,userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
